import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import axios from '../axios';
import store from '../store'

Vue.use(VueRouter);

const routes = [
    {
        path: '/login',
        name: 'login',
        component: () => import('../views/Login.vue')
    },
    {
        path: '/',
        name: 'home',
        component: Home,
        children: [
            {
                path: '/index',
                name: 'index',
                meta: {
                    title: "首页"
                },
                component: () => import('../views/Index.vue')
            },
            {
                path: '/userCenter',
                name: 'userCenter',
                meta: {
                    title: "个人中心"
                },
                component: () => import('../views/sys/UserCenter.vue')
            }
        ]
    }
];

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
});

// Router的前缀拦截，就是在路由到页面之前我们可以做一些判断或者加载数据
router.beforeEach((to, from, next) => {
    let hasRoute = store.state.menus.hasRoute;
    let token = localStorage.getItem("token");
    if (to.path === '/login') {
        next();
    } else if (!token) {
        next({path: '/login'});
    } else if (token && !hasRoute) {
        axios.get("/rookie/menu/nav", {
            headers: {
                Authorization: localStorage.getItem("token")
            }
        }).then(res => {
            // 将menuList放到store
            store.commit("setMenuList", res.data.result.nav);
            // 将用户权限放到store
            store.commit("setPermList", res.data.result.authoritys);
            // 动态绑定路由
            let newRoutes = router.options.routes;
            res.data.result.nav.forEach(menu => {
                if (menu.children) {
                    menu.children.forEach(e => {
                        // 转成路由
                        let route = menuToRoute(e);
                        // 把路由添加到路由管理中
                        if (route) {
                            newRoutes[1].children.push(route)
                        }
                    })
                }
            });
            router.addRoutes(newRoutes);
            hasRoute = true;
            store.commit("changeRouteStatus", hasRoute)
        });
    }
    next()
});

// 导航转成路由
const menuToRoute = (menu) => {
    if (!menu.component) return null;
    return {
        name: menu.name,
        path: menu.path,
        meta: {
            icon: menu.icon,
            title: menu.title
        },
        component: () => import('../views/' + menu.component + '.vue')
    }
};

export default router
